<template>
  <div class="common-layout">
    <el-container v-loading="loading">
      <el-main style="">
        <div>
          <span>当前完整路径: {{ currentDirPath }}</span>
        </div>
        
        <div>
          <h3 style="display: inline-block;margin-right: 100px;">文件列表</h3>
          <div style="display: inline-block;">
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              style="display: inline-block;margin-right: 20px;"
              action="/upload"
              :data = "{'currentPath': currentDirPath}"
              multiple
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :on-success="handleSuccess"
              :on-error="handleError"
              :before-upload="beforeUpload"
              :limit="10"
              :on-exceed="handleExceed"
              :show-file-list="false"
            >
              <el-button type="primary">上传文件</el-button>
            </el-upload>
            <el-button type="success" @click="refreshList">刷新列表</el-button>
            <el-button type="primary" plain @click="dialogVisible=true">新建目录</el-button>
            <el-button type="warning" plain @click="backToRoot">返回根</el-button>
            <el-button type="primary" @click="back">后退</el-button>
          </div>
        </div>
         <el-table :data="tableData" style="width: 80%" :header-cell-style="headerCellStyle">
          <el-table-column prop="type" label="类型" width="80" />
          <el-table-column label="名称" width="500">
              <template #default="scope">
                <span style="cursor: pointer; color: blue; text-decoration: underline;" v-if="scope.row.type=='目录'" @click="enterDir(scope.row)">
                  {{ scope.row.name }}
                </span>
                <span v-else>
                  {{ scope.row.name }}
                </span>
              </template>

          </el-table-column>
          <el-table-column prop="size" label="大小" width="160" />
          <el-table-column label="操作" align="right" width="300">
            <template #default="scope">
              <el-button size="small" v-if="scope.row.type=='文件'" @click="handleDownload(scope.row)">
                下载
              </el-button>
              <el-button size="small" v-if="scope.row.type=='文件'" @click="copyDownloadPath(scope.row)">
                复制地址
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>

    <el-dialog
      v-model="dialogVisible"
      title="创建目录"
      width="30%"
      :before-close="handleClose"
    >
      <el-input v-model="folderName" placeholder="请输入目录名" @keyup.enter="createFolder" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createFolder">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref,onMounted,onActivated, nextTick } from 'vue'
import request from '../api/request';
import { useRouter, useRoute,onBeforeRouteUpdate  } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'
import ClipboardJS from 'clipboard'

const router = useRouter();
const route = useRoute();

const tableData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)

const currentDirPath = ref('/')
const fileList = ref([])
const folderName = ref('')
const copyButton = ref(null);

const headerCellStyle = ({ row, column, rowIndex, columnIndex }) => {
  // 所有表头单元格样式
  const style = {
    'background-color': '#f5f7fa',
    'color': '#303133',
    'font-weight': 'bold',
    'height': '40px'
  };
  
  // 特定列的样式（例如第一列）
  // if (columnIndex === 0) {
  //   style['background-color'] = '#e6f7ff';
  //   style['color'] = '#1890ff';
  // }
  
  return style;
};
const getPath = () =>{
  // 示例：请求后端的/user接口
request.get('/hello')
  .then(response => {
    console.log(response.data);
    currentDirPath.value = response.data
  })
  .catch(error => {
    alert(error);
  });
}

const refreshList = () => {
  loading.value = true
  request.get('/fileList?base='+currentDirPath.value)
    .then(response => {
      console.log(response.data);
      tableData.value = response.data
    })
    .catch(error => {
      alert(error);
    }).finally(() => {
      loading.value = false
    });
}

// 下载文件
const downloadLargeFile = (filePath) => {
  const fileUrl = '/download?filePath='+filePath;
  window.open(fileUrl, '_blank');
};

const handleDownload = (row) => {
  let fullFilePath = currentDirPath.value + "/" + row.name;
  downloadLargeFile(fullFilePath);
}

const copyDownloadPath = (row) => {
  let fullFilePath 
  if(currentDirPath.value.endsWith("/")) {
    fullFilePath = currentDirPath.value + row.name;
  } else {
    fullFilePath = currentDirPath.value + "/" + row.name;
  }
  copyButton.value = document.createElement("button")
  const fileUrl = window.location.origin + '/download?filePath='+fullFilePath;
  const clipboard = new ClipboardJS(copyButton.value, {
    text: () => fileUrl
  });
  clipboard.on('success', () => {
    ElMessage({
      type: 'info',
      message: '已复制到剪贴板!',
    });
    clipboard.destroy();
  });

  clipboard.on('error', () => {
    ElMessage({
      type: 'error',
      message: '复制失败!',
    });
    clipboard.destroy();
  });

  // 触发复制操作
  copyButton.value.click();
}

const deleteFile = (filePath) => {
  loading.value = true
  request.delete('/delete?filePath='+filePath)
   .then(response => {
     refreshList()
    })
    .catch(error => {
      alert(error);
    }).finally(() => {
      loading.value = false
    });
}

const handleDelete = (row) => {
  let fullFilePath = currentDirPath.value + row.name;
  ElMessageBox.confirm(
    `确定删除 ${fullFilePath} ?`,
    '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    }
  ).then(
    () => deleteFile(fullFilePath),
    () => ElMessage({
        type: 'info',
        message: '取消操作',
      })
  )
}
const enterDir = (row) => {
  // currentDirPath.value = currentDirPath.value + row.name + '/';
  // refreshList()
  let tmp = currentDirPath.value.endsWith("/") ? currentDirPath.value : currentDirPath.value+"/"
  const path = tmp + row.name
  console.log("进入新path",path)
  router.push({ path })
}

const back = () => {
  if(currentDirPath.value=='/') {
    ElMessage({
        type: 'info',
        message: '您已经在根目录了',
      })
    return ;
  }
  let tmp = currentDirPath.value.substring(0,currentDirPath.value.length-1)
  let index = tmp.lastIndexOf('/');
  console.log("从", tmp, "后退到", tmp.substring(0, index+1))
  router.push({ path: tmp.substring(0, index+1) })
}
const backToRoot = () => {
  router.push({ path: '/' })
}
const handleRemove= (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 10, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  )
}

const beforeRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}

const handleSuccess = () => {
  loading.value = false
  refreshList()
}
const handleError = (error, uploadFile, uploadFiles) => {
  loading.value = false
  alert(error)
}

const beforeUpload = (evt, uploadFile, uploadFiles) => {
  loading.value = true
}

const createFolder = () => {
  dialogVisible.value = false
  if(!!folderName.value === false || folderName.value.trim().length===0) {
    folderName.value = ''
    alert('请输入目录名')
    return
  }
  loading.value = true
  request.get('/createFolder?folderName='+currentDirPath.value+folderName.value)
    .then(response => {
      refreshList()
    })
    .catch(error => {
      alert(error);
    }).finally(() => {
      folderName.value = ''
      loading.value = false
    });
}

const handleClose = () => {
  dialogVisible.value = false
}

onMounted(()=>{
  if (route.params.part) {
    currentDirPath.value = '/' + route.params.part.join('/');
  } else {
    currentDirPath.value = '/';
  }
  refreshList()
})

// onActivated(() =>  {
//   console.log('activated part', this.$route.params.part);
//   // 如果有参数，则进入指定目录
//   if(route.params.part) {
//     currentDirPath.value = "/"+this.$route.params.part
//     refreshList()
//   }
// })

// 在路径参数改变时执行某些逻辑
onBeforeRouteUpdate((to, from, next) => {
  console.log('路径参数改变:', to.params.part);
  if(to.params.part) {
    currentDirPath.value = "/"+to.params.part.join('/')
  } else {
    currentDirPath.value = "/"
  }
  
  refreshList()
  next();
});



</script>
